package com.junpuxin.component;

import cn.hutool.core.util.StrUtil;
import com.junpuxin.exception.TokenExpiredException;
import com.junpuxin.exception.TokenExpiredSoonException;
import com.junpuxin.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @author junpuxin
 */
@Component
public class TokenInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(@NotNull HttpServletRequest request,
                             @NotNull HttpServletResponse response,
                             @NotNull Object handler) {

        // 若目标方法不是Controller方法，则直接放行
        if (!(handler instanceof HandlerMethod)) return true;
        // 若请求头中不存在Token令牌，则返回失败提示
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)) {
            throw new TokenExpiredException("Token令牌不存在");
        }
        // 解析Token令牌
        Map<String, Object> verifyResult = JwtUtil.parse(token);
        // 获取Token令牌的过期标记：true表示即将要过期
        boolean expiringSoon = (boolean) verifyResult.get("expiringSoon");
        // 若Token令牌即将过期，则返回过期提示以及一个新的Token令牌
        if (expiringSoon) {
            String newToken = (String) verifyResult.get("newToken");
            throw new TokenExpiredSoonException(newToken);
        }
        return true;
    }
}
